package com.cynoware.busappmas.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.cynoware.busappmas.model.Config;

import android.util.Log;

/**
 * 

 */
public class upload {
	
	private final String TAG = "upload";

	 /**
     * 
     * @param urlStr
     * @param filePath
     * @return
     */
	/**
     * 
     * @param urlStr
     * @param filePath
     * @return
     */
	 public String formUpload(String urlStr, String filePath,String uploadSavePath,String param) {
	        String rsp = "";
	        HttpURLConnection conn = null;
	        String BOUNDARY = "|"; 
	        try {
	            URL url = new URL(urlStr);
	            Log.d(TAG,"url ="+urlStr);
	            conn = (HttpURLConnection) url.openConnection();
	            conn.setConnectTimeout(15000);
	            conn.setReadTimeout(15000);
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            conn.setUseCaches(false);
	            conn.setRequestMethod("POST");
	            conn.setRequestProperty("Connection", "Keep-Alive");
	            conn.setRequestProperty("Content-Type",
	                    "multipart/form-data; boundary=" + BOUNDARY);

	            OutputStream out = new DataOutputStream(conn.getOutputStream());
				//file stream
	            File file = new File(filePath);
	            String filename = file.getName();
	            String contentType = "";
	            if (filename.endsWith(".png")) {
	                contentType = "image/png";
	            }
	            if (filename.endsWith(".jpg")) {
	                contentType = "image/jpg";
	            }
	            if (filename.endsWith(".gif")) {
	                contentType = "image/gif";
	            }
	            if (filename.endsWith(".bmp")) {
	                contentType = "image/bmp";
	            }
	            if (filename.endsWith(".txt")){
	            	contentType = "text/plain";
	            }
	            if (contentType == null || contentType.equals("")) {
	                contentType = "application/octet-stream";
	            }
	            StringBuffer strBuf = new StringBuffer();
	            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
	            strBuf.append("Content-Disposition: form-data; name=\"" + param
	                    + "\"; filename=\"" + (uploadSavePath+filename) + "\"\r\n");
	            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
	            out.write(strBuf.toString().getBytes());
	            DataInputStream in = new DataInputStream(new FileInputStream(file));
	            int bytes = 0;
	            byte[] bufferOut = new byte[1024];
	            while ((bytes = in.read(bufferOut)) != -1) {
	                out.write(bufferOut, 0, bytes);
	            }
	            in.close();
	            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
	            out.write(endData);
	            out.flush();
	            out.close();
	            StringBuffer buffer = new StringBuffer();
	            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                buffer.append(line).append("\n");
	            }
	            rsp = buffer.toString();
	            reader.close();
	            reader = null;
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (conn != null) {
	                conn.disconnect();
	                conn = null;
	            }
	        }
	        return rsp;
	    }
	 
	 public boolean uploadGPSInfo(Config mConfig,String filePath){
		 
			if (mConfig==null){
				return false;
			}
			String mSeverIp    = mConfig.getServerIp().getValue();
			String mServerPort = mConfig.getServerPort().getValue();
			String mSubServer  = mConfig.getSubServer().getValue();
			String linenum     = mConfig.getLineNum().getValue();
			String deviceID = mConfig.getDeviceId().getValue();
			String server      = "http://" + mSeverIp + ":" + mServerPort + "/" + mSubServer + "/";
			
			String path = "GetUploadFile";
			String action       = "UploadGPSCollectInfo";
			String postparams = "action="+action+"&linenum=" + linenum + "&device_id="+deviceID;
			String state      = "state--";
			String retString, retCut, ret;
			int    index;
			
			String url = server+path;
			String uploadSavePath = String.format("gps/%s/%s/",linenum,deviceID);
			upload  up = new upload();
			retString = up.formUpload(url,filePath,uploadSavePath,postparams);
			
			boolean upSuccess = false;
			
			if ( retString != null && retString.length() > 0 )
			{
				index  = retString.indexOf(state);
				Log.d(TAG,"----uploadGPSInfo return index= "+index);
				if ( index >= 0 ) {
					retCut = retString.substring(index + state.length(), retString.length());
					ret = retCut.substring(0, 1);
					Log.d(TAG,"----return string= "+ret);
					
					if (Integer.valueOf(ret)==1){
						upSuccess = true;
					}
				}
			}
			return upSuccess;
			
		}

}
